<?php

	if ($_POST['username'] && $_POST['password']) {
		$sql = "SELECT * FROM users WHERE username = '{$_POST['username']}' AND password = AES_ENCRYPT('{$_POST['password']}', '{$_POST['username']}') AND active = 1";
		$qry = db_query($sql);
		if (db_num_rows($qry) == 1) {
			$_SESSION['current_user'] = db_fetch_assoc($qry);
			success("Welcome <em>{$_SESSION['current_user']['first_name']}</em>!");
			if (admin()) location('/admin/'); 
			elseif (isset($_POST['redirect_to'])) location($_POST['redirect_to']);
		} else error('Failed to login. Username / Password combination not found.');
	}
	
	
	if (logged_in()) location();
?>
<form method="post">
	<fieldset>
		<legend>Login Form</legend>
		
	<?php
		if ($_SERVER['REQUEST_URI'] != '/users/login' && $_SERVER['REQUEST_URI'] != '/login.html') {
	?>
	<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']?>" />
	<?php
		}
	?>
	
		<label for="username">
			Username
			<input type="text" name="username" id="username" />
		</label>
		
		<label for="password">
			Password
			<input type="password" name="password" id="password" />
		</label>
		
		<input type="submit" value="Login" />
	</fieldset>
</form>